import React from 'react';
import Container from './Container';
import { WeaTab, WeaDialog, WeaLocaleProvider, WeaTools } from 'ecCom';
import { Button, Icon, Popover, Spin, Alert } from 'antd';
import { observer, inject } from 'mobx-react';
import { WeaForm } from 'comsMobx';
import BoardStore from '../../stores/board/BoardStore';
import { listStore } from '../../stores/list';
import './css/board.css';
import { addEnterFun } from '../../util';
import QuickSearch from '../quickSearch';
import NoRightPage from '../../pages/no-right';
import _ from 'lodash';
import { toJS } from 'mobx';
import jQuery from 'jquery'
import AdvancedSearchs from '../list/AdvancedSearchs';
const getLabel = WeaLocaleProvider.getLabel;
const getTop = WeaTools.WindowFunc.getTop;


export interface BoardProps {
    boardStore: BoardStore,
    location: string,
    Search: listStore
}

@inject('boardStore')
@observer
export default class Board extends React.Component<BoardProps, any>{
    constructor(props) {
        super(props);
        this.state = { showSearchAd: false, orderVisible: false, deleteOrderVisible: false };
        const { boardStore } = props;
        window.onresize = () => {
            boardStore.windowHeight = window.innerHeight;
            boardStore.windowWidth = window.innerWidth;
        };
    }

    componentWillMount() {
        const { boardStore, location } = this.props;
        boardStore.boardid = location['query'].boardid || '';
        boardStore.resourceid = location['query'].rootId || location['query'].rootid || '';
        boardStore.fromPageExpend = location['query'].fromPageExpend || '';
    }

    componentDidMount() {
        const { boardStore } = this.props;
        window['cube_board_open_dialog'] = boardStore.cube_board_open_dialog;
        getTop()['current_boardStore'] = boardStore;
        boardStore.windowHeight = window.innerHeight;
        boardStore.windowWidth = window.innerWidth;

    }

    componentDidUpdate() {
        const { boardStore, location } = this.props;
        let boardid = location['query'].boardid || '';
        let rootid = location['query'].rootId || location['query'].rootid || '';
        if (boardid != boardStore.boardid || rootid != boardStore.resourceid) {
            boardStore.datas = {};
            boardStore.conditionInfo = [];
            boardStore.datasIdList = [];
            boardStore.statusList = [];
            boardStore.form = new WeaForm();
            boardStore.orderField = [];
            boardStore.boardid = boardid;
            boardStore.resourceid = rootid;
            boardStore.initData();
        }
        let doSearch = () => {
            boardStore.doSearch();
            this.setState({ showSearchAd: false })
        }
        addEnterFun(doSearch)
    }

    //nosearch 是否需要查询(单行文本的变动不需要进行查询)
    onChange = (fieldid, value, nosearch?) => {
        const { boardStore } = this.props;
        let { quickSearchFormData, quickSearchData } = boardStore;
        let { quicksearchinfo = [] } = quickSearchData;
        _.set(quickSearchFormData, fieldid, value)
        let resetDate = {} as any;
        //默认值与选择值的筛选，当选择值后，默认值就不会上传，以选择值为主
        quicksearchinfo.map(item => {
            if (!quickSearchFormData[item.fieldid] && quickSearchFormData[item.fieldid] != '') {
                if (item.value && item.value != "") {
                    resetDate[item.fieldid] = item.value;
                } else if (item.fieldhtmltype == "1" && item.fieldtype != '1') {   //浮点数整数单独解析
                    const { options } = item;
                    options.map(key => {
                        const { selected } = key;
                        if (selected) {
                            resetDate[item.fieldid] = key.key;
                        }
                    });
                } else if (item.fieldhtmltype == "3" && item.fieldtype != '1' && item.fieldtype != '2' && item.fieldtype != '19' && item.fieldtype != '290') {   //浏览框也单独解析
                    const { replaceDatas } = item;
                    let ids = "";
                    replaceDatas && replaceDatas.map(rep => {
                        const { id } = rep;
                        ids += id + ",";
                    });
                    ids = ids.substring(0, ids.length - 1);
                    resetDate[item.fieldid] = ids;
                }
            }
            // if (item.fieldid == fieldid && item.fieldhtmltype == '5' && item.fieldtype == '1') {
            //     boardStore.changeQuickSearchData(item.domkey[0])
            // }
        });
        if (!nosearch) {
            let parm = {
                isQuickSearch: "1",
                boardid: boardStore.boardid,
                //groupValue: boardStore.top.selectedKey,
                ...boardStore.quickSearchFormData,
                ...resetDate,
                isOnlyQuick: '1'
            }
            boardStore.doSearch(parm);
        }
    }

    getOrderStyle = (element, type) => {
        const { boardStore } = this.props;
        if (element.fieldid == boardStore.orderInfo.fieldid && type == boardStore.orderInfo.type) {
            return { color: 'rgb(34, 215, 187)' };
        }
        return {}
    }

    renderSearchAdPanel = (boardStore) => {
        //窗口变化后，重新计算高级搜索的面板位置。如果查询条件默认展开，使用默认位置，不计算。
        //if(!boardStore.isShowCondition){
        try {
            const hei = jQuery('.cube_board .wea-tab .ant-row').height() || 46;
            jQuery('.cube_board .wea-tab .wea-search-container ').css({ top: hei });
        } catch (e) { }
        //}
    };

    tabsetShowSearchAd = bool => {
        const { boardStore } = this.props;
        this.setState({
            showSearchAd: bool
        })
        if (bool) {
            this.renderSearchAdPanel(boardStore);
        }
    }

    cancel = () => {
        this.setState({
            showSearchAd: false
        })
    }

    render() {
        const { boardStore } = this.props;
        let { quickSearchData } = boardStore;
        let doSearch = () => {
            boardStore.doSearch();
            this.setState({ showSearchAd: false })
        }
        let leftMargin = '10%';
        if (boardStore.windowTitle != '') {
            document.title = boardStore.windowTitle;
        }
        return !boardStore.hasSearcgRight ? <NoRightPage />
            : <div className="cube_board">
                <Spin spinning={boardStore.data_loading}>
                    <WeaTab searchType={boardStore.isAdvanceSearch ? ['advanced'] : []}
                        showSearchAd={this.state.showSearchAd}
                        setShowSearchAd={this.tabsetShowSearchAd}
                        replaceLeft={quickSearchData.isHasQuickSearch &&
                            <QuickSearch
                                datas={quickSearchData.quicksearchinfo}
                                listStore={boardStore}
                                onChange={this.onChange}
                            />
                        }
                        leftStyle={{
                            width: "100%",
                            paddingRight: leftMargin,
                            boxSizing: "border-box"
                        }}
                        buttons={boardStore.orderField && boardStore.orderField.length > 0 ? [
                            <div onMouseOver={() => { boardStore.orderInfo.type && this.setState({ deleteOrderVisible: true }) }}
                                onMouseLeave={() => { boardStore.orderInfo.type && this.setState({ deleteOrderVisible: false }) }} style={boardStore.orderInfo.type ? { width: '90px', textAlign: 'left' } : { width: '90px', textAlign: 'center' }}>
                                <Popover placement="bottomRight"
                                    content={<div style={{ lineHeight: '25px' }}>
                                        <table>
                                            {boardStore.orderField && boardStore.orderField.map((element, index) => {
                                                return <tr>
                                                    <td><span>{element.fieldlabelname}</span></td>
                                                    <td>
                                                        <span style={{ float: 'right', cursor: 'pointer' }} onClick={() => {
                                                            boardStore.changeOrder(element.fieldid, element.fieldlabelname, element.fieldname, element.viewtype, element.fielddbtype, 'a');
                                                            this.setState({ orderVisible: false });
                                                        }}>
                                                            <Icon style={this.getOrderStyle(element, 'a')} type="arrow-up" />
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <span style={{ float: 'right', cursor: 'pointer', marginRight: '5px' }} onClick={() => {
                                                            boardStore.changeOrder(element.fieldid, element.fieldlabelname, element.fieldname, element.viewtype, element.fielddbtype, 'd');
                                                            this.setState({ orderVisible: false });
                                                        }}>
                                                            <Icon style={this.getOrderStyle(element, 'd')} type="arrow-down" />
                                                        </span>
                                                    </td>
                                                </tr>
                                            })}
                                        </table>
                                    </div>}
                                    trigger="click"
                                    visible={this.state.orderVisible}
                                    onVisibleChange={visible => this.setState({ orderVisible: visible })}
                                >
                                    {boardStore.orderInfo.type ? <span>
                                        <div title={boardStore.orderInfo.fieldlabelname} style={{ width: '66px', textAlign: 'right', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', float: 'left', cursor: 'pointer' }}>
                                            {boardStore.orderInfo.fieldlabelname}
                                        </div><Icon type={boardStore.orderInfo.type == 'a' ? "arrow-up" : "arrow-down"} />
                                    </span>
                                        : <span style={{ cursor: 'pointer', fontSize: '20px', marginTop: '13px', display: 'block' }} title={getLabel(338, "排序")} className="icon-mode-paixu"></span>}
                                </Popover>
                                {this.state.deleteOrderVisible && <span style={{ cursor: 'pointer' }} title={getLabel(389169, "删除排序")} onClick={() => {
                                    boardStore.clearOrderInfo();
                                    this.setState({ deleteOrderVisible: false });
                                }} className="icon-coms-Clear"></span>}
                            </div>
                        ] : []}
                        buttonsAd={[
                            (<Button type="primary" onClick={doSearch}>{getLabel(387355, "搜索")}</Button>),
                            (<Button type="ghost" onClick={boardStore.form.reset}>{getLabel(2022, "重置")}</Button>),
                            (<Button type="ghost" onClick={this.cancel}>{getLabel(201, "取消")}</Button>)
                        ]}
                        searchsAd={
                            <AdvancedSearchs form={boardStore.form} conditioninfo={boardStore.conditionInfo}  quickSearch={doSearch} />
                        }
                        advanceHeight={'auto'}
                    />
                    {undefined != boardStore.checkAdvanedData && boardStore.checkAdvanedData != '' ?
                        <Alert message={toJS(boardStore.checkAdvanedData)}
                            type="warning"
                            closable
                            onClose={v => {
                                window.console && console.log("Search.checkAdvanedData:", boardStore.checkAdvanedData)
                            }}
                        /> : ''
                    }
                    <Container {...this.props} />
                    <WeaDialog
                        onCancel={() => { boardStore.cardDiag_visible = false }}
                        visible={boardStore.cardDiag_visible}
                        style={{ width: boardStore.windowWidth - 50, height: boardStore.windowHeight - 60 }}
                        hasScroll
                        url={boardStore.cardDiag_url}
                        className="cube_board_dialog"
                    />
                </Spin>
            </div>
    }
}
